package 多线程;

import java.awt.*;

/**
 * @Author: 朱胜伟
 * @CreateTime: 2021-02-03 09:08
 * @Description:
 */
public class ShenXiao {
    public static void main(String[] args) {
        ValueOP valueOP = new ValueOP();
        ConsumerThread consumerThread3 = new ConsumerThread(valueOP);
        ConsumerThread consumerThread1 = new ConsumerThread(valueOP);
        ConsumerThread consumerThread2 = new ConsumerThread(valueOP);
        ProducerThread producerThread1 = new ProducerThread(valueOP);
        ProducerThread producerThread2 = new ProducerThread(valueOP);
        ProducerThread producerThread3 = new ProducerThread(valueOP);

        producerThread1.start();
        producerThread2.start();
        producerThread3.start();
        consumerThread1.start();
//        consumerThread2.start();
//        consumerThread3.start();
    }
}
//模拟生产者
class ConsumerThread extends Thread{
    private ValueOP obj;
    public ConsumerThread(ValueOP o){
        super();
        this.obj = o;
    }

    @Override
    public void run() {
        while (true){
            obj.getValue();
        }
    }
}
//模拟生产者
class ProducerThread extends Thread{
    private ValueOP obj;
    public ProducerThread(ValueOP o){
        super();
        this.obj = o;
    }

    @Override
    public void run() {
        while (true){
            obj.setValue();
        }
    }
}
class ValueOP{
    private Object key1 = new Object();
    private Object key2 = new Object();
    private String value = "";
    //设置
    public void setValue(){
        synchronized (this){
            while (!value.equals("")){
                try {
                    System.err.println(Thread.currentThread().getName()+"等待");
                    this.wait();
                    System.err.println(Thread.currentThread().getName()+"等待结束");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            String value = System.currentTimeMillis()+"_"+ System.nanoTime();
            System.out.println("set设置的值是:"+value);
            this.value = value;
            //this.notify() 多对多会造成假死
            this.notifyAll();
        }
    }
    //获取
    public void getValue(){
        synchronized (this){
            while (value.equals("")){
                try {
                    System.err.println(Thread.currentThread().getName()+"等待");
                    this.wait();
                    System.err.println(Thread.currentThread().getName()+"等待结束");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("get的值:"+this.value);
            this.value = "";
            //this.notify() 多对多会造成假死
            this.notifyAll();
        }
    }
}
